package com.hl.toolkit.server.suning.epp.demo;

/*
 * Copyright (C), 2002-2015, 苏宁易购电子商务有限公司
 * FileName: demo.java
 * Author:   14074534
 * Date:     2015-5-19 上午10:17:35
 * Description: //模块目的、功能描述      
 * History: //修改记录
 * <author>      <time>      <version>    <desc>
 * 修改人姓名             修改时间            版本号                  描述
 */

import com.suning.SuNingConfig;
import com.suning.epps.codec.Digest;
import com.suning.epps.codec.RSAUtil;
import com.suning.util.Util;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.ParseException;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpUriRequest;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.security.PrivateKey;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.Map.Entry;


/**
 * 〈一句话功能简述〉<br> 
 * 〈功能详细描述〉
 *
 * @author 14074534
 * @see [相关类/方法]（可选）
 * @since [产品/模块版本] （可选）
 */
public class QueryOrderDemo {
	
	
	private static String publicKeyIndex = "0001";
	private static String signAlgorithm = "RSA";
 	private  static String inputCharset = "UTF-8";
    /**
     * 私钥
     */
/**	private static final String PRIVATE_KEY = "MIICeAIBADANBgkqhkiG9w0BAQEFAASCAmIwggJeAg"
        + "EAAoGBALb_y4p_Fj3yyaukPXU43h1ZZ3f3MVG2JT5FIxRacHxWarboPPviL4nkZPbU7YNQ8YrAdT"
        + "zfsv8Est6jOxVXwcTplRcnWKe86j_fVH2LwOLjVcT2YMuCq8vk6wqNFrm5FpHs8MToibbrLay0Mh"
        + "PVMDv_QEHL1FSb3jIp2Y185MSXAgMBAAECgYEAq9Dm7hX8cBVwO_NssI7AHJZAi2ZPrAR0W07WbN"
        + "mtG1CXyTurZmMrdzA1i3rHta9d2YRxjsIJcV6cAmUHqDZI-l5SaGUNI5W4uq5tFVenvgNEvYQsRz"
        + "JWPfYtkFCgXG38CNu-v8G3lEbptxUa8jfBhYDYsqyAFuktY8eILfmqaOECQQDZ8brK_ANYVKeXy2"
        + "eeYz8uikr_JCpTRbwc4_BPOuGQ604GhY3CqvHh5heJbZUnYjJRZh-P7QkJ67cEqQe2E_yVAkEA1v"
        + "P-0dzlv_I83q1ECdXV_C0tRtwxfdNDeAhoJjD-7CPqFeH5FsMi1d1u7eI0A0cmtYgKv1yfOQ_3Wv"
        + "4TPY2FewJAFjiZTPzo8mafN9DbXcDMvlgHUYBEeH0RsvhilhFw0i_LosqXK5P2WYv2NmLf5EYUz0"
        + "vUR_5o_4PzAxyg1qWvCQJBANSK2rJkfAC545pDNP2MpVP-z8A7ReymkxYDKghpdgfE01fj40qwlK"
        + "dnlqI9gzSijBH_fLEPQplHwkwE4r2ATDUCQQDMJmDsuubnHNUADCDin6NR9cyQRK1Y1QNuhK6xU_"
        + "vEUTRMY9BkHJGXo1hQHirH5sr6Y8K3zx7cYgbKiyUG1IgX";**/
//	private static PayProperties prop = new PayProperties();

    public static void main(String args[]) throws Throwable {
    	
        String submitTime= new SimpleDateFormat("yyyyMMddHHmmss").format(new Date());
        String orderTime= new SimpleDateFormat("yyyyMMddHHmmss").format(new Date());
       String outOrderNo=Util.generalBatchNo();
        Map<String, String> requestMap = new HashMap<String, String>();
         requestMap.put("merchantNo", SuNingConfig.merchantNo);
        requestMap.put("publicKeyIndex", publicKeyIndex);
        requestMap.put("signAlgorithm", signAlgorithm);
        requestMap.put("inputCharset", inputCharset);
        requestMap.put("submitTime", submitTime);
        requestMap.put("outOrderNo", outOrderNo);
        requestMap.put("orderTime", orderTime);
        requestMap.put("signature", generateSignature(requestMap));
        // 打印最终url
        System.out.println(mosaicUrlWithParams(SuNingConfig.QueryOrderUrl, requestMap));
    }
    
    public static String buildRequest(Map<String, String> requestMap) throws Throwable {
        //Map<String, String> requestMap = new HashMap<String, String>();
        String submitTime= new SimpleDateFormat("yyyyMMddHHmmss").format(new Date());
         requestMap.put("merchantNo", SuNingConfig.merchantNo);
         requestMap.put("publicKeyIndex", publicKeyIndex);
         requestMap.put("signAlgorithm", signAlgorithm);
         requestMap.put("inputCharset", inputCharset);
        requestMap.put("submitTime", submitTime);
        //requestMap.put("outOrderNo", requestMap.get("outOrderNo"));
        //requestMap.put("orderTime", "20150119000000");
        //requestMap.put("outOrderNo", "2015071312090936396");
        //requestMap.put("orderTime", "20150722102631");
        requestMap.put("signature", generateSignature(requestMap));

        String result = post(SuNingConfig.QueryOrderUrl, requestMap);
        // 打印最终提交的form表单
        System.out.println("查询结果：" + result);
        return result;
    }

    /**
     * 
     * 功能描述: <br>
     * 生成签名
     * 
     * @param requestMap
     * @return
     * @see [相关类/方法](可选)
     * @since 20150325
     */
    public static String generateSignature(Map<String, String> requestMap) {
        System.out.println("开始生成签名");
        List<String> excudeKeylist = new ArrayList<String>();
        excudeKeylist.add("signature");
        excudeKeylist.add("signAlgorithm");
        String[] excudeKey = new String[excudeKeylist.size()];
        String digest = Digest.digest(requestMap, excudeKeylist.toArray(excudeKey));
        System.out.println("digest : " + digest);
        String sign = null;
        try {
        	PrivateKey privateKey = RSAUtil.resolvePrivateKey("D:/RSA/private.key");

            sign = RSAUtil.sign(digest, privateKey);
        } catch (Throwable e) {
            System.err.println("生成签名失败");
        }
        System.out.println("sign : " + sign);
        return sign;
    }


    public static String mosaicUrlWithParams(String url, Map<String, String> params) {
        StringBuilder paramStr = new StringBuilder();
        for (Entry<String, String> entry : params.entrySet()) {
            paramStr.append(entry.getKey()).append("=").append(entry.getValue()).append("&");
        }
        return url + "?" + paramStr.substring(0, paramStr.length() - 1);

    }
    
    /**
     * This method gets hidden type HTML element using passed name and value.
     * 
     * @param paramName
     * @param paramValue
     * @return
     */
    private static String buildInputHiddenFieldInForm(String paramName, String paramValue) {
        String line = "<input type=\"hidden\" name=\"\" value=\"\">";
        if (paramName == null || paramValue == null) {
            return "";
        } else {
            int nameSize = "name=".length() + 1;
            int valueSize = "value=".length() + 1;
            line = line.substring(0, line.indexOf("name=") + nameSize) + paramName
                    + line.substring(line.indexOf("name") + nameSize);
            line = line.substring(0, line.indexOf("value=") + valueSize) + paramValue
                    + line.substring(line.indexOf("value=") + valueSize);
            return line;
        }
    }
    
    /**
     * 拼装form表单
     * 
     * @return
     */
    private static String buildForm(String url, String inputFiled) {

        StringBuffer form = new StringBuffer();
        form.append("<form name=\"punchout_form\" method=\"post\" action=\"");
        form.append(url);
        form.append("\">");
        form.append(inputFiled);
        form.append("<input type=\"submit\" value=\"确认\" style=\"display:none;\"></form>");
        form.append("<script>document.forms['punchout_form'].submit();</script>");
        return form.toString();
    }
    
    public static String post(String url, Map<String, String> params) {  
        DefaultHttpClient httpclient = new DefaultHttpClient();  
        String body = null;  
          
        HttpPost post = postForm(url, params);  
          
        body = invoke(httpclient, post);  
          
        httpclient.getConnectionManager().shutdown();  
          
        return body;  
    }  
      
//    public static String get(String url) {  
//        DefaultHttpClient httpclient = new DefaultHttpClient();  
//        String body = null;  
//
//        HttpGet get = new HttpGet(url);  
//        body = invoke(httpclient, get);  
//          
//        httpclient.getConnectionManager().shutdown();  
//          
//        return body;  
//    }  
          
      
    private static String invoke(DefaultHttpClient httpclient,  
            HttpUriRequest httpost) {  
          
        HttpResponse response = sendRequest(httpclient, httpost);  
        String body = paseResponse(response);  
          
        return body;  
    }  
    
    private static HttpResponse sendRequest(DefaultHttpClient httpclient,  
            HttpUriRequest httpost) {  
        HttpResponse response = null;  
          
        try {  
            response = httpclient.execute(httpost);  
        } catch (ClientProtocolException e) {  
            e.printStackTrace();  
        } catch (IOException e) {  
            e.printStackTrace();  
        }  
        return response;  
    }  
    
    private static HttpPost postForm(String url, Map<String, String> params){  
        
        HttpPost httpost = new HttpPost(url);  
        List<NameValuePair> nvps = new ArrayList <NameValuePair>();  
          
        Set<String> keySet = params.keySet();  
        for(String key : keySet) {  
            nvps.add(new BasicNameValuePair(key, params.get(key)));  
        }  
          
        try {  
            httpost.setEntity(new UrlEncodedFormEntity(nvps, HTTP.UTF_8));  
        } catch (UnsupportedEncodingException e) {  
            e.printStackTrace();  
        }  
        return httpost;  
    }  
    
    private static String paseResponse(HttpResponse response) {  
        HttpEntity entity = response.getEntity();  
        String body = null;  
        try {  
            body = EntityUtils.toString(entity);  
        } catch (ParseException e) {  
            e.printStackTrace();  
        } catch (IOException e) {  
            e.printStackTrace();  
        }  
          
        return body;  
    }  
}
